//
//  LoginViewController.m
//  Molian
//
//  Created by 胡津 on 15/3/30.
//  Copyright (c) 2015年 xiaocan. All rights reserved.
//
#define btnSize 70


#import "LoginViewController.h"
#import "RegisterViewController.h"
#import "MLLoginTextField.h"
#import "InitDataViewController.h"
#import "VerificationnumberViewController.h"
#import "ForgotpasswordViewController.h"
#import "WXApi.h"
#import "AppDelegate.h"
#import <TencentOpenAPI/TencentOAuth.h>
#import "ThirdpartyPhoneViewController.h"
@interface LoginViewController ()

@property (nonatomic, strong) MLLoginTextField *userID;
@property (nonatomic, strong) MLLoginTextField *userPassWord;

@end

@implementation LoginViewController
{
    AppDelegate *appDelegate;
}

-(void)leftItem
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(void)Forgotpassword
{
    [self.navigationController pushViewController:[[ForgotpasswordViewController alloc]init] animated:YES];
    
}

-(void)ssoWeiXinPressed
{
    //构造SendAuthReq结构体
    SendAuthReq* req =[[SendAuthReq alloc ] init];
    req.scope = @"snsapi_userinfo" ;
    req.state = @"wxaa055b4833fdbf4a" ;
    //第三方向微信终端发送一个SendAuthReq消息结构
    [WXApi sendReq:req];

}

- (void)dealloc
{
     [[NSNotificationCenter defaultCenter] removeObserver:self];
     // [[NSNotificationCenter defaultCenter] removeObserver:self name:@"WXLogin" object:nil];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"登录";
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(WXLogin:) name:@"WXLogin" object:nil];
  
    
    appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];

    
    //隐藏返回按钮
   // self.navigationItem.hidesBackButton =YES;
//    self.view.backgroundColor = [UIColor whiteColor];
//    UIBarButtonItem *leftItem  = [[UIBarButtonItem alloc]initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(leftItem)];
//    self.navigationItem.leftBarButtonItem = leftItem;
    /*
    //一登刷脸按钮
    UIButton*btn_SuperID=[self buttonStyle:@" 登刷脸按钮" image:@"LOGO_64x64" action:@selector(loginWithSuperID:)];
    btn_SuperID.frame=CGRectMake(30, DeviceHeight-153, DeviceWidth-60, 40);
    [self.view addSubview:btn_SuperID];
    */
    

    
    self.userID = [[MLLoginTextField alloc]initWithFrame:CGRectMake(20, 100, DeviceWidth-40, 40)];
    self.userID.placeholder = @"输入手机号";
    self.userID.text = [Utils defaultsForKey:@"accountName"];
    self.userID.leftImage = [UIImage imageNamed:@"id_icon"];
    self.userID.keyboardType = UIKeyboardTypePhonePad;
    [self.userID style];
    [self.view addSubview:self.userID];
    
    self.userPassWord = [[MLLoginTextField alloc]initWithFrame:CGRectMake(20, 150, DeviceWidth-40, 40)];
    self.userPassWord.placeholder = @"输入密码";
    self.userPassWord.secureTextEntry = YES;
    self.userPassWord.leftImage = [UIImage imageNamed:@"password_icon"];
    [self.userPassWord style];
    [self.view addSubview:self.userPassWord];
    
    UIButton *forgetpassword = [[UIButton alloc]initWithFrame:CGRectMake((DeviceWidth-100)/2, 200, 100, 30)];
    [forgetpassword setTitle:@"忘记密码?" forState:UIControlStateNormal];
    [forgetpassword setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    forgetpassword.titleLabel.font = [UIFont fontWithName:FontName size:14];
    [forgetpassword addTarget:self action:@selector(Forgotpassword) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:forgetpassword];
    
    //登陆按钮
    BFPaperButton *LOGIN = [[BFPaperButton alloc]initWithFrame:CGRectMake(20, 260, DeviceWidth-40, 45 )raised:NO];
    [LOGIN setTitle:@"登录" forState:UIControlStateNormal];
    [LOGIN setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    LOGIN.layer.masksToBounds = YES;//开启圆角
    [LOGIN setBackgroundImage:[UIImage imageWithColor:APPCOLOR(1)] forState:UIControlStateNormal];
    [LOGIN.layer setCornerRadius:CGRectGetHeight([LOGIN bounds]) / 2];
    LOGIN.titleLabel.font = [UIFont fontWithName:FontName size:14];
    [LOGIN addTarget:self action:@selector(LOGIN:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:LOGIN];

    //注册按钮
    BFPaperButton *registerBtn = [[BFPaperButton alloc]initWithFrame:CGRectMake(20, 325, DeviceWidth-40, 45 )raised:NO];
    [registerBtn setTitle:@"注册" forState:UIControlStateNormal];
    [registerBtn setTitleColor:APPCOLOR(1) forState:UIControlStateNormal];
    registerBtn.layer.masksToBounds = YES;//开启圆角
    [registerBtn.layer setCornerRadius:CGRectGetHeight([registerBtn bounds]) / 2];
    registerBtn.titleLabel.font = [UIFont fontWithName:FontName size:14];
    [registerBtn.layer setBorderColor:APPCOLOR(1) .CGColor];
    [registerBtn.layer setBorderWidth:1];
    [registerBtn addTarget:self action:@selector(registerBtn) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:registerBtn];
    
    
    if (!IS_IPHONE_4) {
        UILabel *other = [[UILabel alloc]initWithFrame:CGRectMake(0, DeviceHeight-130, DeviceWidth, 30)];
        [other setText:@"其他登录方式"];
        [other setTextAlignment:NSTextAlignmentCenter];
        [other setTextColor:[UIColor grayColor]];
        [other setFont:[UIFont fontWithName:FontName size:14]];
        [self.view addSubview:other];
    }
    //微博按钮
    
    UIButton*btn_weibo=[self buttonStyle:@"" image:@"microblog" action:@selector(ssoButtonPressed)];
    btn_weibo.frame=CGRectMake(btnSize-10, DeviceHeight-90, btnSize, btnSize);
    [self.view addSubview:btn_weibo];
    
    if ([WXApi isWXAppInstalled]) {
        //已经安装
        //微信按钮
        UIButton*btn_weixin=[self buttonStyle:@"" image:@"wechat" action:@selector(ssoWeiXinPressed)];
        btn_weixin.frame=CGRectMake((DeviceWidth-btnSize)/2, DeviceHeight-90, btnSize, btnSize);
        [self.view addSubview:btn_weixin];
   }
    
    
   if([TencentOAuth iphoneQQInstalled]){
       
        //QQ按钮
        UIButton*btn_qq=[self buttonStyle:@"" image:@"qq" action:@selector(ssoQQPressed)];
        btn_qq.frame=CGRectMake(DeviceWidth-(btnSize+btnSize-10), DeviceHeight-90, btnSize, btnSize);
        [self.view addSubview:btn_qq];
        
    }
    
    
 
    
    [self.view addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(returnKeyBorad)]];
    
}

//回收键盘
-(void)returnKeyBorad
{
    [self.view endEditing:YES];
}

-(void)LOGIN:(UIButton*)sender
{
    [self.view endEditing:YES];
    sender.enabled = NO;
    // 账号登录
    NSString *accountName = self.userID.text;
    NSString *password = self.userPassWord.text;
    
    [Utils saveToDefaults:accountName forKey:@"accountName"];
    
    
    // 验证输入的参数
    BOOL isParamValid = [self verifyLoginParam:accountName password:password];
    if (!isParamValid) {
        sender.enabled = YES;
        return;
    }
    
    // 异步登录
    [MPUser logInWithMobilePhoneNumberInBackground:accountName password:password block:^(AVUser *user, NSError *error) {
        // 停止转菊花
        [HUD hideFromViewAnimated:YES];
        sender.enabled = YES;
        if (!error) {
            // 账号被禁用的处理
            MPUser *cuser = (MPUser *)user;
            if (MPUserStatus_DISABLE == cuser.status) {
                [appDelegate appout];
                return;
            }
            // 判断是否完成账号初始化
            if (!cuser.isUserInited) {
                InitDataViewController *initDataView = [[InitDataViewController alloc]init];
                [initDataView.navigationItem setHidesBackButton:YES animated:YES];
                [self.navigationController pushViewController:initDataView animated:YES];
                return;
            }
            // 通知登录成功
            [appDelegate loginToEasemob];
            [self dismissViewControllerAnimated:YES completion:nil];
        } else {
            // 登录失败
            NSString *msg = @"登录失败";
            if (AVOS_RES_CODE_PWD_ERROR == error.code) {
                msg = @"登录失败,密码错误";
            } else if (AVOS_RES_CODE_USER_NOT_EXIST == error.code) {
                msg = @"登录失败,账号不存在";
            } else if (AVOS_RES_CODE_PHONE_NOT_VERIFIED == error.code) {
                // 账号还没有验证, 跳转到验证账号页面
                msg = @"该手机号还没有通过验证, 请输入收到的验证码";
                [HUD Prompt:msg ];
                
                // 向该用户发送验证码
                [MPUser requestMobilePhoneVerify:accountName withBlock:^(BOOL succeeded, NSError *error) {
                    if (succeeded) {
                        NSLog(@"获取验证码成功");
                    }
                }];
                
                VerificationnumberViewController *mobileVerifyView = [[VerificationnumberViewController alloc]init];
                mobileVerifyView.phoneNumber = accountName;
                mobileVerifyView.password = password;
                // 隐藏返回按钮
                [mobileVerifyView.navigationItem setHidesBackButton:YES animated:YES];
                
                [self.navigationController pushViewController:mobileVerifyView animated:YES];
                
                return;
            }
            [HUD Prompt:msg];
        }
    }];
    // 转菊花
    [HUD setOnViewWithTitle:nil animated:YES];

}

//登录判断
- (BOOL)verifyLoginParam:(NSString *)accountName password:(NSString *)password {
    if (!accountName || [accountName isEqualToString:@""]) {
        [HUD Prompt:@"请输入手机号"];
        return NO;
    } else if (!password || [password isEqualToString:@""]) {
        [HUD Prompt:@"请输入密码"];
        return NO;
    } else if (password.length < 6 || password.length > 16) {
        [HUD Prompt:@"密码应该是6-16个字符"];
        return NO;
    }
    return YES;
}


-(void)registerBtn
{
    [self.navigationController pushViewController:[[RegisterViewController alloc]init] animated:YES];
}


-(void)back
{
    [self.navigationController popToRootViewControllerAnimated:YES];
}

-(UIButton *) buttonStyle:(NSString*)title image:(NSString*)imagenamed action:(SEL)selector
{
    UIButton*button=[UIButton buttonWithType:UIButtonTypeCustom];
    [button setTitle:title forState:UIControlStateNormal];
    [button setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [button setImage:[UIImage imageNamed:imagenamed] forState:0];
    [button addTarget:self action:selector forControlEvents:UIControlEventTouchUpInside];
    button.titleLabel.font = [UIFont fontWithName:FontName size:20];
    return button;
}

//微博sso登录
- (void)ssoButtonPressed
{

    [self dismissViewControllerAnimated:YES completion:^{
       
        [AVOSCloudSNS setupPlatform:AVOSCloudSNSSinaWeibo withAppKey:WEIBO_APP_KEY andAppSecret:@"908a23ac28cc7af983def4b6b8180138" andRedirectURI:WEIBO_REDIRECT_URI];
        
        [AVOSCloudSNS loginWithCallback:^(id object, NSError *error) {
            NSLog(@"-----------%@-------",object);
            [MPUser loginWithAuthData:object platform:@"weibo" block:^(AVUser *user, NSError *error) {
                
                if (![MPUser currentUser].isUserInited) {
                    if (object) {
                        InitDataViewController *InitData = [[InitDataViewController alloc]init];
                        InitData.isThirdparty = YES;
                        InitData.nickname = [object objectForKey:@"username"];
                        InitData.gender = [[[object objectForKey:@"raw-user"] objectForKey:@"gender"] isEqualToString:@"m"] ? 1:2 ;
                        
                        NSString *location = [[object objectForKey:@"raw-user"] objectForKey:@"location"];
                        NSString *district = [[NSString alloc]init];
                        NSString *city = [[NSString alloc]init];
                        
                        if (location.length > 2) {
                            district = [location substringToIndex:[location rangeOfString:@" "].location];
                            city = [location substringWithRange:NSMakeRange(district.length+1, location.length-district.length-1)];
                        }else{
                            district = location;
                            city = @"";
                        }
                        
                        
                        InitData.location = @[district,city];
                        InitData.userAvatarURL = [[object objectForKey:@"raw-user"] objectForKey:@"avatar_hd"];
                        [InitData.navigationItem setHidesBackButton:YES animated:YES];
                        [Utils pushTabbarHidden:InitData Selfvc:self];
                    }
                    
                }else{
                    [appDelegate loginToEasemob];
                     [self dismissViewControllerAnimated:YES completion:nil];
                }
                

                
            }];
            
        } toPlatform:AVOSCloudSNSSinaWeibo];
        
    }];
 

}

-(void)ssoQQPressed
{
//    [self dismissViewControllerAnimated:YES completion:nil];
    
    [AVOSCloudSNS setupPlatform:AVOSCloudSNSQQ withAppKey:QQ_APP_ID andAppSecret:QQ_APP_KEY andRedirectURI:nil];
    
    [AVOSCloudSNS loginWithCallback:^(id object, NSError *error) {
        NSLog(@"-----------%@-------",object);
        
        [MPUser loginWithAuthData:object platform:@"qq" block:^(AVUser *user, NSError *error) {
            //返回AVUser
            if (![MPUser currentUser].isUserInited) {
                if (object) {
                    InitDataViewController *InitData = [[InitDataViewController alloc]init];
                    InitData.isThirdparty = YES;
                    InitData.nickname = [object objectForKey:@"username"];
                    InitData.gender = [[[object objectForKey:@"raw-user"] objectForKey:@"gender"] isEqualToString:@"男"] ? 1:2 ;
                    
                    NSString *location = [[object objectForKey:@"raw-user"] objectForKey:@"province"];
                    NSString *city = [[object objectForKey:@"raw-user"] objectForKey:@"city"];
                    InitData.location = @[location,city];
                    
                    InitData.userAvatarURL = [[object objectForKey:@"raw-user"] objectForKey:@"figureurl_qq_2"];
                    
                    [InitData.navigationItem setHidesBackButton:YES animated:YES];
                    [self.navigationController pushViewController:InitData animated:YES];

                }
            }else{
                [appDelegate loginToEasemob];
                [self dismissViewControllerAnimated:YES completion:nil];
            }
           
        }];
        
    } toPlatform:AVOSCloudSNSQQ];
    
}

-(void)WXLogin:(NSNotification *)notification
{
    NSDictionary *object=[notification userInfo];    
    
    //    [MPUser loginWithAuthData:object block:^(AVUser *user, NSError *error) {
    //        InitDataViewController *InitData = [[InitDataViewController alloc]init];
    //        InitData.nickname = [object objectForKey:@"nickname"];
    //        InitData.gender = [[object objectForKey:@"sex"] integerValue];
    //
    //
    //        InitData.userAvatarURL = [object objectForKey:@"headimgurl"];
    //
    //        [InitData.navigationItem setHidesBackButton:YES animated:YES];
    //        [self.navigationController pushViewController:InitData animated:YES];
    //    }];
    
    
    
    [MPUser loginWithAuthData:object platform:AVOSCloudSNSPlatformWeiXin block:^(AVUser *user, NSError *error)  {
        
//        MPUser *currentUser = [MPUser currentUser];
        [MPUser loginWithAuthData:object platform:@"weixin" block:^(AVUser *user, NSError *error) {
            if (![MPUser currentUser].isUserInited) {
                if (object) {
                    InitDataViewController *InitData = [[InitDataViewController alloc]init];
                    InitData.isThirdparty = YES;
                    InitData.nickname = [object objectForKey:@"nickname"];
                    InitData.gender = [[object objectForKey:@"sex"] integerValue];
                    InitData.userAvatarURL = [object objectForKey:@"headimgurl"];
                    
                    [InitData.navigationItem setHidesBackButton:YES animated:YES];
                    [self.navigationController pushViewController:InitData animated:YES];
                }
            }else{
                [appDelegate loginToEasemob];
                [self dismissViewControllerAnimated:YES completion:nil];
                
                
            }
        }];
        
    }];
    
}




/*
 -(void)viewWillAppear:(BOOL)animated
 {
 [super viewWillAppear:animated];
 superIdSdk = [SuperID sharedInstance];
 superIdSdk.delegate = self;
 }
 
 -(void)loginWithSuperID:(id)sender {
 NSError *error = nil;
 //获取⼀一登登录VC,如调⽤用有phone接⼝口,在参数phoneNumber中传⼊入⼿手机号码即可。
 id SIDLoginViewController = [superIdSdk obtainLoginViewControllerWithError:&error];
 if (SIDLoginViewController) {
 //开发者须采⽤用present⽅方式弹出⼀一登登录VC
 [self presentViewController:SIDLoginViewController animated:YES completion
 :nil];
 }else{
 NSLog(@"loginView Error =%ld,%@",(long)[error code],@"网络异常");
 }
 }
 
 
 
 - (void)superID:(SuperID *)sender userDidFinishLoginWithUserInfo:(NSDictionary *)userInfo withAppUid:(NSString *)uid error:(NSError *)error{
 NSLog(@"%@",userInfo);
 
 if (!error) {
 [self.navigationController setNavigationBarHidden:NO animated:YES];
 
 UIBarButtonItem *leftBarButtonItem  = [[UIBarButtonItem alloc]initWithTitle:@"退出" style:UIBarButtonItemStylePlain target:self action:@selector(back)];
 self.navigationItem.leftBarButtonItem = leftBarButtonItem;
 
 [HUD Prompt:[NSString stringWithFormat:@"欢迎回来%@",[userInfo objectForKey:@"name"]] Content:nil Timer:5];
 
 //用户登录成功的执行内容
 //        [self back];
 
 }else{
 //用户登录失败的执行内容
 NSLog(@"loginView Error =%ld,%@",(long)[error code],@"网络异常");
 }
 }
 */

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    if ([self isViewLoaded]&&!self.view.window) {
        self.view = nil;
    }
    // Dispose of any resources that can be recreated.

}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
